(function(app){
	app
	.controller("loginCtrl",["$scope","$rootScope","$ionicPopup","$timeout","$state","$http","$ionicLoading","loginFac","Alert","Userinfo","HttpGet",
	function($scope,$rootScope,$ionicPopup,$timeout,$state,$http,$ionicLoading,loginFac,Alert,Userinfo,HttpGet){
		$rootScope.flowCurrentTitle = 1;
		$rootScope.contentStyle = "plm-add-tab";
		$rootScope.isIos = isiOS;
		$rootScope.android = isAndroid;
		$rootScope.loop = 0;
//		clearInterval($rootScope.loop);
		
		$scope.getDomian = false;
		$scope.autoLogin = false;
		
		if (isiOS) {
			document.getElementById("iosBody").style.backgroundColor = "#e8ebf2";
		}
		
		$rootScope.plmAlert = function(alertMsg,dayLay){
			var myPopup = $ionicPopup.show({title: alertMsg});
           	$timeout(function(){myPopup.close();},dayLay);
		};
		
		if(typeof(WebViewJavascriptBridge) == "undefined"){
				$rootScope.autoLogin = true;
				$rootScope.hostNameData = {
					deviceId:'3f5fda0d44f287d31bd23091a71aad50a80310af',
					channelId:'3698168517276129437',
					ip:"10.8.20.4",
					mac:"123",
					deviceType:3,
					deviceVersion:'4.4.0'
				};
		};
		
		if(isiOS){
			setupWebViewJavascriptBridge(function(bridge){
				bridge.registerHandler('oc_hostName', function(data, responseCallback) {
					
					$rootScope.hostNameData = data;
					
					if ('1' == data.isIphoneX) {
						$rootScope.isIphoneX = true;
					} else {
						$rootScope.isIphoneX = false;
					}
					if ('1' == data.isiPad) {
						$rootScope.isiPad = true;
					} else {
						$rootScope.isiPad = false;
					}
					
					var c=data.deviceVersion.split('.');
					
					$rootScope.iosVersion = c[0];
					
					if (isiOS && parseInt($rootScope.iosVersion) < 11) {
						var iosHeight = document.documentElement.clientHeight - 20;
						document.getElementById("iosMg").style.height= iosHeight+'px';
					}
					
					var callBackData = {version:data.version,deleteTime:FILE_SAVE_DATA};
					if("true" == data.autoLoginFlag){$rootScope.autoLogin = true;}
					else{$rootScope.autoLogin = false;}
					if($rootScope.autoLogin && "" !== data.username){
						
						var loginName = data.username,
							passWord = data.passwd,
							hostIp = data.ip,
							hostName = data.deviceId,
							mac = data.mac,
							channelId = data.channelId,
							deviceType = 4,
							deviceVersion = data.deviceVersion;
							
						$scope.views.loginName = loginName;
						$scope.views.passWord = passWord;
						
						$scope.autoLogin = true;
						if ($scope.getDomian) {
							$scope.views.UserLogin(loginName,passWord,hostName,channelId,deviceType,deviceVersion);
						}
					}
				});
			});
		}else if(isAndroid){
			setTimeout(
				function(){if(typeof(WebViewJavascriptBridge)!=="undefined"){
					var callBackData = {version:WEB_APP_VERSON,deleteTime:FILE_SAVE_DATA};
					WebViewJavascriptBridge.callHandler('oc_getHostName',callBackData,function(response){
						$rootScope.hostNameData = eval('(' + response + ')');
						if("true" == $rootScope.hostNameData.autoLoginFlag){$rootScope.autoLogin = true;}
						else{$rootScope.autoLogin = false;}
						if($rootScope.autoLogin && '' !== $rootScope.hostNameData.username){
							var loginName = $rootScope.hostNameData.username,
								passWord = $rootScope.hostNameData.passwd,
								hostName =  $rootScope.hostNameData.deviceId,
								channelId = $rootScope.hostNameData.channelId,
								deviceType = 3,deviceVersion = $rootScope.hostNameData.deviceVersion;							
							$scope.views.loginName = loginName;
							$scope.views.passWord = passWord;
							
							$scope.autoLogin = true;
							if ($scope.getDomian) {
//								$scope.views.UserLogin(loginName,passWord,hostName,channelId,deviceType,deviceVersion);
							}
						}
						if(!(WEB_APP_VERSON == $rootScope.hostNameData.version)){
							var confirmPopup = $ionicPopup.confirm({title: "版本更新",cancelText: '取消',okText: '确定',});
							confirmPopup.then(function(res) {
								if(res){
//									var downLoadUrl = {
//										//FilePath:"http://cloud.intekey.com/IntePLM/IntePlmApp.apk",
//										FilePath:APP_URL,
//										MainFileName:"",
//										isBigSize:true,
//										fileId:0,
//										modifyTime:"2100/01/01 00:00:00"
//									};
									var downLoadUrl = {
										url:APP_URL
									};
									WebViewJavascriptBridge.callHandler('oc_openUrl',downLoadUrl,function(response){console.log(response);});
								}
								else{confirmPopup.close();}
							});
						}
					});
				}}
			,"2000"); //2秒后再调用，要不然WebViewJavascriptBridge还没初始化完成
		};
		
		
		
//		$scope.views.loginName = $rootScope.loginName;
//		$scope.views.passWord = $rootScope.passWord;
		
		$scope.views = {
			loginName:'',
			passWord:'',
			deviceId:"",
			isDomainCheck:0,
			selectedDomain:'',
			moveStyle:"",
			
			login:function(){
				$scope.views.moveDown();
				document.body.scrollIntoView();
				$rootScope.flowCurrentTitle = 1;
//				$rootScope.contentStyle = "plm-add-tab";
				
				if(typeof(WebViewJavascriptBridge) == "undefined"){
					$rootScope.autoLogin = true;
					$rootScope.hostNameData = {
						deviceId:'madskd',
						channelId:'3698168517276129437',
						ip:"10.8.20.4",
						mac:"123",
						deviceType:3,
						deviceVersion:'4.4.0'
					};
				};
				
				var loginName = $scope.views.loginName;
				var passWord = $scope.views.passWord;
				var hostName = $rootScope.hostNameData.deviceId;
				var channelId = $rootScope.hostNameData.channelId;
				var deviceType = 3;
				var deviceVersion = $rootScope.hostNameData.deviceVersion;
				if(isiOS){deviceType = 4;}else{deviceType = 3;}
				if("" == loginName || "" == passWord){$rootScope.plmAlert("登录名和密码不能为空！",1500);}
				else{$scope.views.UserLogin(loginName,passWord,hostName,channelId,deviceType,deviceVersion);}
			},
			UserLogin:function(loginname,loginpwd,hostName,channelId,deviceType,deviceVersion){
				if($scope.domainCheck == 0){
        				$scope.views.isDomainCheck = 0;
       		 	}
				var data = {
	            		operateType:'userLogin',
					loginName:loginname,
					loginPwd:loginpwd,
					channelId:channelId,
					mobileGuid:hostName,
					domainCheck:$scope.views.isDomainCheck,
					domainName:$scope.views.selectedDomain
    				}
				postCfg = {
					headers: {'Content-Type': 'application/x-www-form-urlencoded'},
			    		transformRequest: function (data) {
						var str = [];
						for(var p in data){
							str.push(encodeURIComponent(p) + "=" + encodeURIComponent(data[p]));
						}
						return str.join("&");
			    		}
				}
				$ionicLoading.show({
					template: 'Loading...'
				});
				
					HttpGet.get(
						SERVER_IP + '/handler/Login.ashx'
            		).then(function (result) {
            			$ionicLoading.hide();
					if (result.success == "1") {
                    		console.log(result);
                    		
                    		$rootScope.loginName = $scope.views.loginName;
						$rootScope.passWord = $scope.views.passWord;
						
                    		
                    		Userinfo.add('loginName', result.loginName);
                    		Userinfo.add('forbidCheckSelf', result.forbidCheckSelf);
                    		Userinfo.add('userId', result.userId);
                    		Userinfo.add('roleId', result.roleId);
                    		Userinfo.add('userName', result.userName);
                    		Userinfo.add('userPower', result.userPower);
                    		Userinfo.add('toKen', result.toKen);
                    		
                    		
                    		$rootScope.myFlowData = [];
						$rootScope.todoFlowData = [];
						$rootScope.completedFlowData = [];
						$rootScope.copyFlowData = [];
                    		
                    		$rootScope.hideTabs = false;
                    		
                    		var httpTail = '&toKen='+Userinfo.get('toKen')+'&userId='+Userinfo.get('userId');
                    		
                    	HttpGet.get(SERVER_IP + 'app/main/handler/Main.ashx?operateType=getAppMenu'+ httpTail
						    ).then(function (data) {
//						    	{"titleName":"车间文档","tabMenu":[{"menuId":"1","menuName":"我的文档","menuImage":"resources/images/mobile/mydocument","menuUrl":"tab/mydoc","menuUrlName":"tab-mydoc"},{"menuId":"2","menuName":"设置","menuImage":"resources/images/mobile/set","menuUrl":"tab/set","menuUrlName":"tab-set"}]}
									if(data != null && data != ""){
										console.log(data);
										$rootScope.titleName = data.titleName;
										$rootScope.tabMenu = data.tabMenu;
//										$state.go(data.tabMenu[0].menuUrlName.replace("-","."),{menu_index:0},{reload:true});
										location.href = "#/"+data.tabMenu[0].menuUrl + "?menu_index=0";
//										$state.go("tab.flow");
									}else{
										Alert.plmAlert("获取导航栏失败",1000);
									}

						        });    
                    		
                    		if (isiOS) {
                    			
                    			document.getElementById("iosBody").style.backgroundColor = "#33A5DB";
                    		}
                    		if(typeof(WebViewJavascriptBridge) !== "undefined"){
							WebViewJavascriptBridge.callHandler('oc_setUserInfo',{'username':$scope.views.loginName,'passwd':$scope.views.passWord},function(response){});
						}
                    		
                    } else {
						Alert.plmAlert(result.message,1000);
                    }
                });
			},
			doServer:function(){
				console.log("服务器设置");
				if(typeof(WebViewJavascriptBridge) !== "undefined"){
					WebViewJavascriptBridge.callHandler('oc_setServerInfo','',function(response){});
				};
			},
			moveUp: function(){
				if (isiOS && parseInt($rootScope.iosVersion) < 13) {
					if ($rootScope.isiPad) {
						$scope.views.moveStyle = "login-move-up2";
					} else {
						$scope.views.moveStyle = "login-move-up";
					}
				}
			},
			moveDown: function(){
				$scope.views.moveStyle = "";
				var input = document.getElementById("input-name");
				$scope.views.loginName = input.value;
			},
			moveDown2: function(){
				$scope.views.moveStyle = "";
			}
		};
		
		document.addEventListener('focusout',function(){
			window.scrollTo();
//			document.body.scrollTop = 0;
//  			document.documentElement.scrollTop = 0;
		});
		
		
		HttpGet.get(
	    	SERVER_IP + '/handler/Login.ashx?operateType=systemInit'
	    ).then(function (data) {
//	        	{"systemNameCh":"东电技术资料实物管控","systemNameEn":"东电技术资料实物管控","domainCheck":"0","domainAllowed":"intekey.com(10.8.20.234);aaabb(10.2.2.2);ccc(10.8.8.8);","systemTitleCh":"东电技术资料实物管控","systemTitleEn":"东电技术资料实物管控"}
					console.log(data);
					$scope.domainCheck = data.domainCheck;
					if ($scope.domainCheck == 0) {
						$scope.views.selectedDomain = '';
					} else {		
						var domains = data.domainAllowed.substring(0, data.domainAllowed.length-1);
						$scope.domain = domains.split(";");
						console.log($scope.domain);
						$scope.views.selectedDomain = $scope.domain[0].split('(')[1].split(')')[0];
					}
					
					$scope.getDomian = true;
					if ($scope.autoLogin) {
						var loginName = $scope.views.loginName;
						var passWord = $scope.views.passWord;
						var hostName = $rootScope.hostNameData.deviceId;
						var channelId = $rootScope.hostNameData.channelId;
						var deviceType = 3;
						var deviceVersion = $rootScope.hostNameData.deviceVersion;
						if(isiOS){deviceType = 4;}else{deviceType = 3;}
						$scope.views.UserLogin(loginName,passWord,hostName,channelId,deviceType,deviceVersion);
						
					}
	        });

	}])
	
	
})(app)